using AdvVerifyModels.Models.Responses.SubstrateTracking;
using AdvVerifyModels.SubstrateTracking;
using Microsoft.EntityFrameworkCore;
using StackExchange.Redis;

namespace WaferServviceDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Services.AddDbContextFactory<ApplicationDbContext>(options => options
                .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
                .UseSqlite(builder.Configuration.GetConnectionString("Database")));

            builder.Services.AddSingleton(_ =>
                ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("RedisConfiguration")!));

            builder.Services.AddSingleton<SubstrateTrackingService>();
            builder.Services.AddTransient<FoupService>();

            var app = builder.Build();
            app.UseExceptionHandler(_ => { });

            app.MapPost("/track", static async (SubstrateTrackingService service) =>
            {
                var result = await service.Track();
                return Results.Ok(result);
            });

            app.MapPost("/open_foup/{foup}", static (int foup, FoupService service) =>
            {
                var id = service.Open(foup);
                return Results.Ok(new WaferServiceResponse
                {
                    Id = id
                });
            });

            app.Run();
        }
    }

    public class FoupService(SubstrateTrackingService substrateTrackingService)
    {
        public Guid Open(int foup)
        {

            var id = Guid.NewGuid();
            _ = OpenAsync(id, 1);
            return id;
        }

        async Task OpenAsync(Guid guid, int foup)
        {
            try
            {
                await substrateTrackingService.SendEvent(new FoupOpenEvent
                {
                    TrackingId = guid,
                    Foup = foup,
                    Slots = new WaferState[1] { WaferState.Loading }
                });
            }
            catch (Exception ex)
            {
            }
        }
    }
}
